package com.example.network_android;

import android.app.Activity;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class HostActivity extends Activity {

	Server server;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_host);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_host, menu);
        return true;
    }

    @Override
    protected void onResume() {
    	super.onResume();
    	
    	
    	TextView v = (TextView)findViewById(R.id.textView_ip);
    	
    	WifiManager wifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
    	WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    	int ip = wifiInfo.getIpAddress();
    	
    	String ipString = String.format(
    			"%d.%d.%d.%d",
    			(ip & 0xff),
    			(ip >> 8 & 0xff),
    			(ip >> 16 & 0xff),
    			(ip >> 24 & 0xff));
    	
		v.setText(ipString);
		
		final Handler h = new Handler();
		Thread t = new Thread(new Runnable() {

			public void run() {
				while(true){
					if(server!=null){
			    	Log.d("Network_android", "listening...");
			    	
			    	final String answer = server.listen();
			    	h.post(new Runnable(){

						public void run() {
							((TextView)findViewById(R.id.textView_input)).setText(answer);
							
						}
			    		
			    	});
			    	
			    	Log.d("Network_android", "listening completed");
					}
					else {
				    	server = new Server();
					}
				}
			}
			
		});
		t.start();
    	
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                NavUtils.navigateUpFromSameTask(this);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }


}
